<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box{
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      left: 0;
      top: 0;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <script>
    // 同步和异步 => 是一种消息通知机制
    // 方块的运动
    function move(ele, attr, target, cd){
      let start = parseFloat(window.getComputedStyle(ele, null)[attr]);
      let dis = (target - start) / Math.abs(target - start);
      let speed = dis * 5;

      function fn(){
        let now = parseFloat(window.getComputedStyle(ele, null)[attr]);
        if(now == target){
          cd && cd('运动完成！');
        } else {
          ele.style[attr] = now + speed + 'px';
          // 异步
          window.requestAnimationFrame(fn); // 性能更好
          // setTimeout(fn, 10);
        }
      }

      fn()
    }

    let ele = document.querySelector('.box');

    // 回调地狱
    move(ele, 'left', 200, function(res){
      console.log(res);
      move(ele, 'top', 200, function(res){
        console.log(res);
      })
    });
  </script>
</body>
</html>